import * as ElementUI from 'element-ui'
import router from './router'
import store from './store'
import axios from 'axios'
import 'vue-axios'



/* 开发、生产环境地址 */
switch (process.env.NODE_ENV) {
    case 'development':
        axios.defaults.baseURL = "http://localhost";
        break;
    case  'production':
        axios.defaults.baseURL = "http://localhost";
        break;
}

/* 请求拦截器 */
axios.interceptors.request.use(
    config => {
        console.log("发送请求："+config.url);
        /* 发送请求时，带上token */
        if (store.getters.token) {
            config.headers.Authorization = store.getters.token;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

/* 响应拦截器 */
axios.interceptors.response.use(
    response =>{
        console.log("响应状态为："+response.status);
        console.log(response.data);
        /* 响应码为200代表成功 */
        if(response.data.code != 200){
            ElementUI.Message.warning(response.data.message);
            switch (response.data.code) {
                case 4001:
                    console.log("登录失败");
                    router.push("/login");
                    break;
                case 4002:
                    console.log("需要登录访问");
                    router.replace({path: "/login"});
                    break;
                case 4003:
                    console.log("访问拒绝");
                    break;
            }
        }else{
            //ElementUI.Message.info(response.data.message);
        }
        /* 提取有效载荷 */
        response.data = response.data.data;
        return response;
    },
    error=>{
        console.log("请求错误："+error);
        return Promise.reject(error);
    });

export default axios;
